#!/usr/bin/env bash

# ----------------------------------------------------------------------
# Filename:   newPasswd-dcredit.sh
# Version:    1.0
# Date:       2021/03/30
# Author:     laiyixin
# Email:      laiyixin@kylinos.com.cn
# History：
#             Version 1.0, 2021/03/30
# Function:   newPasswd-dcredit - 用户密码中必须至少包含多少个数字
# Out:
#              0=> Success
#              1=> Fail
#              other=> TCONF
# ----------------------------------------------------------------------

## TODO: 使用ctrl+c退出
##
newPasswdOnCtrlC() {
    echo "正在优雅的退出..."
    newPasswdClean

    exit ${TFAIL}
}

## TODO: 用户界面
##
newPasswdUSAGE() {
    cat >&1 <<EOF
--------- newPasswd-dcredit - 用户密码中必须至少包含多少个数字 ---------
EOF
}

## TODO : 执行前的初始化
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
newPasswdInit() {
    # 判断root用户
    if [ $(id -u) -ne 0 ]; then
        echo "Must use root ！"
        exit ${TCONF}
    fi

    # 信号捕获ctrl+c
    trap 'newPasswdOnCtrlC' INT

    newPasswdClean

}

## TODO : 执行进行时的方法
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
newPasswdTest() {
    while read pamFile; do
        if grep -w pam_pwquality.so "${pamFile}" &>/dev/null; then
            sed -ri "s/(^\s*[^#].*pam_pwquality.so\s.*)dcredit=\S+\s(.*)/\1\2/g" "${pamFile}" &&
                sed -ri "s/(^\s*[^#].*pam_pwquality.so\s)(.*)/\1dcredit=${dcredit} \2/g" "${pamFile}"
            newPasswdRetParse "pam_pwquality.so dcredit=${dcredit} ${pamFile}"
        fi
    done < <(find /etc/pam.d -type f)
}

## TODO : 执行收尾清除工作
##
newPasswdClean() {
    echo "Clean ..."

}

## TODO: 解析函数返回值
## In  : $1 => log
newPasswdRetParse() {
    local ret=$?
    local logstr=""

    if [ $# -eq 1 ]; then
        logstr="$1"
    fi

    if [ $ret -eq 0 ]; then
        echo "[pass] : ${logstr}"
    else
        echo "[fail] : ${logstr}"
        newPasswdClean
        exit ${TFAIL}
    fi
}

## TODO : Main
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
newPasswdMain() {
    newPasswdUSAGE

    newPasswdInit

    newPasswdTest

    newPasswdClean

    return ${TPASS}
}

newPasswdMain
exit $?
